<?php
/*
 * rdAuth Component for rdBloggery
 *
 * @author      gwoo <gwoo@rd11.com>
 * @version     0.10.8.2176
 * @license		OPPL
 *
 */
class rdAuthComponent
{
	var $components = array('Session');
	
	/**
	* id of the logged in user
	*
	* @var unknown_type
	* @access private
	*/
	var $id = null;
	
	/**
	* login_id of the logged in user
	*
	* @var string
	* @access private
	*/
	var $login_id = null;
	
	/**
	* role assigned to the logged in user
	*
	* @var string
	* @access private
	*/
	var $role = null;
	
	var $name = null;

	/**
	* if admins passes then set admin var
	*
	* @var bool
	* @access private
	*/
	var $admin = null;
	/**
	* if role assigned to the logged in user matches admins array
	*
	* @var array
	* @access private
	*/
	var $admins = array();
	
	/**
	* Error messages to be displayed if the user is short of access for the requested action.
	*
	* @var string
	* @access private
	*/
	var $errors = null;
	/**
	* Function to check the session and return local vars
	*
	* @param string $data used for login method
	* @return errors
	*/
	function set($data='')
	{
		if($data)
		{
			$this->Session->write('rdAuth.id', $data['id']);
			$this->Session->write('rdAuth.login_id', $data['login_id']);
			$this->Session->write('rdAuth.role', $data['member_role']);
			$this->Session->write('rdAuth.name', $data['name_kanji']);
		}
		if($this->Session->check('rdAuth') && $this->Session->valid('rdAuth'))
		{
			$this->id = $this->Session->read('rdAuth.id');
			$this->login_id = $this->Session->read('rdAuth.login_id');
			$this->role = $this->Session->read('rdAuth.role');
			$this->name = $this->Session->read('rdAuth.name');
			if(in_array($this->role,$this->admins))
			{
				$this->admin = 1;	
			}
		}
		elseif($this->Session->error())
		{
			return $this->Session->error();
		}
	}
	
	/**
	* logout method deletes session
	*
	* @return errors
	*/
	function logout()
	{
		$this->Session->del('rdAuth.id');
		$this->Session->del('rdAuth.login_id');
		$this->Session->del('rdAuth.role');
		$this->Session->del('rdAuth.name');
		$this->Session->del('rdAuth');
		if($this->Session->error())
		{
			return $this->Session->error();
		}
	}
	
	/**
	* Function to check the access for the action based on the access list
	*
	* @param string $action The action for which we need to check the access
	* @param array $access Access array for the controller's actions
	* @return boolean
	*/
	function check($action, $access = '')
	{
		if (is_array($access) && array_key_exists($action, $access))
		{
			if($this->role)
			{	
				if (in_array($this->role, $access[$action]['role']))
				{
					return true;
				}
				else
				{
					return false; 
				}
			}
			else
			{
				return false; 
			}
		}
		return	true;
	} 
}